package com.bjzsly.star3.xzb.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by admin on 2017/5/9.
 */

public class PermissionUtil {


    public static void checkPermission(Activity act) {

        List<String> permissions = getRequirePermissions(act);
        if (permissions.size() > 0) {
            ActivityCompat.requestPermissions(act, permissions.toArray(new String[permissions.size()]), 0);
        }

    }

    public static int checkRequirePermissions(Activity act) {
        List<String> permissions = getRequirePermissions(act);
        if (permissions.size() > 0) {
            return permissions.size();
        }
        return -1;
    }

    public static List<String> getRequirePermissions(Activity act) {
        List<String> permissions = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(act, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.CAMERA);
            }

            if (ContextCompat.checkSelfPermission(act, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }

            if (ContextCompat.checkSelfPermission(act, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            
            if(ContextCompat.checkSelfPermission(act, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.READ_PHONE_STATE);
            }
        }

        return permissions;
    }

    public static boolean checkWritePermission(Activity act) {
        try {
            return ContextCompat.checkSelfPermission(act, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        } catch (Exception e) {
        }
        return false;
    }


    public static void requestPermission(Activity act, String permission) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                ActivityCompat.requestPermissions(act, new String[]{permission}, 0);
            }
        } catch (Exception e) {
        }
    }

    public static boolean checkPermission(Context context, String pemission) {

        try {
            return ContextCompat.checkSelfPermission(context,pemission) == PackageManager.PERMISSION_GRANTED;
        } catch (Exception e) {
        }
        return false;
    }
}
